/*
 * Copyright 2009 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kitwee.com.kanpad.orderDetail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.kitwee.serialport.callback.SerialPortCallback;
import com.kitwee.serialport.data.model.SerialPortData;
import com.kitwee.serialport.data.model.SerialPortParam;
import com.kitwee.serialport.util.SerialPortFinder;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import kitwee.com.kanpad.BaseActivity;
import kitwee.com.kanpad.R;

public class SerialPortActivity extends BaseActivity {

    @BindView(R.id.et_device_id)
    EditText etDeviceId;
    @BindView(R.id.et_url)
    EditText etUrl;
    @BindView(R.id.et_time)
    EditText etTime;
    private Spinner mDeviceSpinner;
    private Spinner mBaudratesSpinner;
    private Spinner mDatabitsSpinner;
    private Spinner mParitySpinner;
    private Spinner mStopbitsSpinner;

    private TextView mReceivedData;

    private SerialPortFinder mFinder;

    private Toast mToast;

    public static void start(Context context) {
        Intent intent = new Intent(context, SerialPortActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.serial_port_act);
        ButterKnife.bind(this);
        initializeData();
        initializeViews();
    }

    private String mDevice;
    private String mBaudrates;
    private String mDatabits;
    private String mParity;
    private String mStopbits;

    private List<String> mDeviceArray;
    private List<String> mDevicePathArray;

    private List<String> mBaudratesArray;
    private List<String> mDatabitsArray;
    private List<String> mParityArray;
    private List<String> mStopbitsArray;

    private void initializeData() {
        mFinder = new SerialPortFinder();
        SerialPortPreferences.initialize(getApplicationContext());

        mDeviceArray = Arrays.asList(mFinder.getAllDevices());
        mDevicePathArray = Arrays.asList(mFinder.getAllDevicesPath());

        mBaudratesArray = getStringArrayAsList(R.array.baudrates);
        mStopbitsArray = getStringArrayAsList(R.array.stopbits);
        mDatabitsArray = getStringArrayAsList(R.array.databits);
        mParityArray = getStringArrayAsList(R.array.parity);

        mDevice = SerialPortPreferences.getDevicePath();
        mDatabits = SerialPortPreferences.getDatabits();
        mStopbits = SerialPortPreferences.getStopbits();
        mParity = SerialPortPreferences.getParity();
        mBaudrates = SerialPortPreferences.getBaudRate();

    }

    private void initializeViews() {
        mDeviceSpinner = find(R.id.spinner_device);
        mDeviceSpinner.setAdapter(new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, mDeviceArray
        ));
        if (mDevice != null) {
            mDeviceSpinner.setSelection(mDevicePathArray.indexOf(mDevice));
        }

        mBaudratesSpinner = find(R.id.spinner_baudrates);
        mBaudratesSpinner.setAdapter(new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, mBaudratesArray
        ));
        if (mBaudrates != null) {
            mBaudratesSpinner.setSelection(mBaudratesArray.indexOf(mBaudrates));
        }

        mDatabitsSpinner = find(R.id.spinner_databits);
        mDatabitsSpinner.setAdapter(new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, mDatabitsArray
        ));
        if (mDatabits != null) {
            mDatabitsSpinner.setSelection(mDatabitsArray.indexOf(mDatabits));
        }

        mParitySpinner = find(R.id.spinner_parity);
        mParitySpinner.setAdapter(new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, mParityArray
        ));
        if (mParity != null) {
            mParitySpinner.setSelection(mParityArray.indexOf(mParity));
        }

        mStopbitsSpinner = find(R.id.spinner_stopbits);
        mStopbitsSpinner.setAdapter(new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_dropdown_item, mStopbitsArray
        ));
        if (mStopbits != null) {
            mStopbitsSpinner.setSelection(mStopbitsArray.indexOf(mStopbits));
        }

        mReceivedData = find(R.id.received_data);

        find(R.id.btn_connect).setOnClickListener(mClickListener);
        find(R.id.btn_save).setOnClickListener(mClickListener);
    }


    private View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getSelectedItem();
            switch (v.getId()) {
                case R.id.btn_save:
                    savePreferences();
//                    openSerialPort();
                    popupMessage("配置保存成功");
                    finish();
                    break;
                case R.id.btn_connect:
//                    openSerialPort();
                    popupMessage("已应用当前配置");
                    break;
            }
        }
    };

    private void openSerialPort() {
        SerialPortParam param = new SerialPortParam.Builder()
                .devicePath(mDevice)
                .baudRate(mBaudrates)
                .databits(mDatabits)
                .stopbits(mStopbits)
                .parity(mParity)
                .build();
        SerialPortHelper.getInstance(this)
                .openSerialPort(param);
    }

    @Override
    protected void onStart() {
        super.onStart();
        SerialPortHelper.getInstance(this).addCallback(mDataCallback);
    }

    private SerialPortCallback mDataCallback = new SerialPortCallback() {
        @Override
        public void onSuccess(SerialPortData data) {
            mReceivedData.append(data.getFlag() + " , " + data.getData() + "\n");
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        SerialPortHelper.getInstance(this).removeCallback(mDataCallback);
    }

    private void popupMessage(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }

    private void getSelectedItem() {
//        mDevice = mDevicePathArray.get(mDeviceSpinner.getSelectedItemPosition());
        mBaudrates = (String) mBaudratesSpinner.getSelectedItem();
        mStopbits = (String) mStopbitsSpinner.getSelectedItem();
        mDatabits = (String) mDatabitsSpinner.getSelectedItem();
        mParity = (String) mParitySpinner.getSelectedItem();
    }

    private void savePreferences() {
        SerialPortPreferences.saveDeivcePath(mDevice);
        SerialPortPreferences.saveBaudRate(mBaudrates);
        SerialPortPreferences.saveParity(mParity);
        SerialPortPreferences.saveDatabits(mDatabits);
        SerialPortPreferences.saveStopbits(mStopbits);
        if (etDeviceId.getText() != null) {
            SerialPortPreferences.saveDeviceId(etDeviceId.getText().toString());
        }
        if (etUrl.getText() != null) {
            SerialPortPreferences.saveUploadUrl(etUrl.getText().toString());
        }
        if (etTime.getText() != null) {
            SerialPortPreferences.saveTimeSpa(etTime.getText().toString());
        }


    }


    private List<String> getStringArrayAsList(int arrayResId) {
        return Arrays.asList(getResources().getStringArray(arrayResId));
    }


}
